home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Mac-Source 1994 July
/
Mac-Source_July_1994.iso
/
Other Langs
/
python
/
emacs-info
/
python-lib.info-2
< prev
next >
Encoding:
Amiga
Atari
Commodore
DOS
FM Towns/JPY
Macintosh
Macintosh JP
Macintosh to JP
NeXTSTEP
RISC OS/Acorn
Shift JIS
UTF-8
Wrap
GNU Info File
|
1994-04-01
|
49.4 KB
|
1,277 lines
|
[
TEXT/R*ch
]
This is Info file python-lib.info, produced by Makeinfo-1.55 from the
input file lib.texi.
This file describes the built-in types, exceptions and functions and the
standard modules that come with the Python system. It assumes basic
knowledge about the Python language. For an informal introduction to
the language, see the Python Tutorial. The Python Reference Manual
gives a more formal definition of the language. (These manuals are not
yet available in INFO or Texinfo format.)
Copyright (C) 1991, 1992, 1993, 1994 by Stichting Mathematisch Centrum,
Amsterdam, The Netherlands.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
File: python-lib.info, Node: array, Next: math, Prev: __main__, Up: Built-in Modules
Built-in module `array'
=======================
This module defines a new object type which can efficiently represent
an array of basic values: characters, integers, floating point numbers.
Arrays are sequence types and behave very much like lists, except that
the type of objects stored in them is constrained. The type is
specified at object creation time by using a "type code", which is a
single character. The following type codes are defined:
*Typecode*
*Type* -- *Minimal size in bytes*
`'c''
character -- 1
`'b''
signed integer -- 1
`'h''
signed integer -- 2
`'i''
signed integer -- 2
`'l''
signed integer -- 4
`'f''
floating point -- 4
`'d''
floating point -- 8
The actual representation of values is determined by the machine
architecture (strictly spoken, by the C implementation). The actual
size can be accessed through the TYPECODE attribute.
The module defines the following function:
- function of module array: array (TYPECODE, INITIALIZER)
Return a new array whose items are restricted by TYPECODE, and
initialized from the optional INITIALIZER value, which must be a
list or a string. The list or string is passed to the new array's
`fromlist()' or `fromstring()' method (see below) to add initial
items to the array.
Array objects support the following data items and methods:
- data of module array: typecode
The typecode character used to create the array.
- data of module array: itemsize
The length in bytes of one array item in the internal
representation.
- function of module array: append (X)
Append a new item with value X to the end of the array.
- function of module array: byteswap (X)
"Byteswap" all items of the array. This is only supported for
integer values. It is useful when reading data ffrom a file
written on a machine with a different byte order.
- function of module array: fromfile (F, N)
Read N items (as machine values) from the file object F and append
them to the end of the array. If less than N items are available,
`EOFError' is raised, but the items that were available are still
inserted into the array.
- function of module array: fromlist (LIST)
Appends items from the list. This is equivalent to `for x in
LIST: a.append(x)' except that if there is a type error, the array
is unchanged.
- function of module array: fromstring (S)
Appends items from the string, interpreting the string as an array
of machine values (i.e. as if it had been read from a file using
the `fromfile()' method).
- function of module array: insert (I, X)
Insert a new item with value X in the array before position I.
- function of module array: tofile (F)
Write all items (as machine values) to the file object F.
- function of module array: tolist ()
Convert the array to an ordinary list with the same items.
- function of module array: tostring ()
Convert the array to an array of machine values and return the
string representation (the same sequence of bytes that would be
written to a file by the `tofile()' method.)
When an array object is printed or converted to a string, it is
represented as `array(TYPECODE, INITIALIZER)'. The INITIALIZER is
omitted if the array is empty, otherwise it is a string if the TYPECODE
is `'c'', otherwise it is a list of numbers. The string is guaranteed
to be able to be converted back to an array with the same type and
value using reverse quotes (```'). Examples:
array('l')
array('c', 'hello world')
array('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.14])
File: python-lib.info, Node: math, Next: time, Prev: array, Up: Built-in Modules
Built-in Module `math'
======================
This module is always available. It provides access to the
mathematical functions defined by the C standard. They are:
- function of module math: acos (X)
- function of module math: asin (X)
- function of module math: atan (X)
- function of module math: atan2 (X, Y)
- function of module math: ceil (X)
- function of module math: cos (X)
- function of module math: cosh (X)
- function of module math: exp (X)
- function of module math: fabs (X)
- function of module math: floor (X)
- function of module math: fmod (X, Y)
- function of module math: frexp (X)
- function of module math: ldexp (X, Y)
- function of module math: log (X)
- function of module math: log10 (X)
- function of module math: modf (X)
- function of module math: pow (X, Y)
- function of module math: sin (X)
- function of module math: sinh (X)
- function of module math: sqrt (X)
- function of module math: tan (X)
- function of module math: tanh (X)
Note that `frexp' and `modf' have a different call/return pattern than
their C equivalents: they take a single argument and return a pair of
values, rather than returning their second return value through an
`output parameter' (there is no such thing in Python).
The module also defines two mathematical constants:
- data of module math: pi
- data of module math: e
File: python-lib.info, Node: time, Next: regex, Prev: math, Up: Built-in Modules
Built-in Module `time'
======================
This module provides various time-related functions. It is always
available. (On some systems, not all functions may exist; e.g. the
"milli" variants can't always be implemented.)
An explanation of some terminology and conventions is in order.
* The "epoch" is the point where the time starts. On January 1st
that year, at 0 hours, the "time since the epoch" is zero. For
UNIX, the epoch is 1970. To find out what the epoch is, look at
the first element of `gmtime(0)'.
* UTC is Coordinated Universal Time (formerly known as Greenwich Mean
Time). The acronym UTC is not a mistake but a compromise between
English and French.
* DST is Daylight Saving Time, an adjustment of the timezone by
(usually) one hour during part of the year. DST rules are magic
(determined by local law) and can change from year to year. The C
library has a table containing the local rules (often it is read
from a system file for flexibility) and is the only source of True
Wisdom in this respect.
* The precision of the various real-time functions may be less than
suggested by the units in which their value or argument is
expressed. E.g. on most UNIX systems, the clock "ticks" only
every 1/50th or 1/100th of a second, and on the Mac, it ticks 60
times a second.
Functions and data items are:
- data of module time: altzone
The offset of the local DST timezone, in seconds west of the 0th
meridian, if one is defined. Only use this if `daylight' is
nonzero.
- function of module time: asctime (TUPLE)
Convert a tuple representing a time as returned by `gmtime()' or
`localtime()' to a 24-character string of the following form:
`'Sun Jun 20 23:21:05 1993''. Note: unlike the C function of the
same name, there is no trailing newline.
- function of module time: ctime (SECS)
Convert a time expressed in seconds since the epoch to a string
representing local time. `ctime(t)' is equivalent to
`asctime(localtime(t))'.
- data of module time: daylight
Nonzero if a DST timezone is defined.
- function of module time: gmtime (SECS)
Convert a time expressed in seconds since the epoch to a tuple of 9
integers, in UTC: year (e.g. 1993), month (1-12), day (1-31), hour
(0-23), minute (0-59), second (0-59), weekday (0-6, monday is 0),
julian day (1-366), dst flag (always zero). Fractions of a second
are ignored. Note subtle differences with the C function of this
name.
- function of module time: localtime (SECS)
Like `gmtime' but converts to local time. The dst flag is set to
1 when DST applies to the given time.
- function of module time: millisleep (MSECS)
Suspend execution for the given number of milliseconds. (Obsolete,
you can now use use `sleep' with a floating point argument.)
- function of module time: millitimer ()
Return the number of milliseconds of real time elapsed since some
point in the past that is fixed per execution of the python
interpreter (but may change in each following run). The return
value may be negative, and it may wrap around.
- function of module time: mktime (TUPLE)
This is the inverse function of `localtime'. Its argument is the
full 9-tuple (since the dst flag is needed). It returns an
integer.
- function of module time: sleep (SECS)
Suspend execution for the given number of seconds. The argument
may be a floating point number to indicate a more precise sleep
time.
- function of module time: time ()
Return the time as a floating point number expressed in seconds
since the epoch, in UTC. Note that even though the time is always
returned as a floating point number, not all systems provide time
with a better precision than 1 second. An alternative for
measuring precise intervals is `millitimer'.
- data of module time: timezone
The offset of the local (non-DST) timezone, in seconds west of the
0th meridian (i.e. negative in most of Western Europe, positive in
the US, zero in the UK).
- data of module time: tzname
A tuple of two strings: the first is the name of the local non-DST
timezone, the second is the name of the local DST timezone. If no
DST timezone is defined, the second string should not be used.
File: python-lib.info, Node: regex, Next: marshal, Prev: time, Up: Built-in Modules
Built-in Module `regex'
=======================
This module provides regular expression matching operations similar to
those found in Emacs. It is always available.
By default the patterns are Emacs-style regular expressions; there is a
way to change the syntax to match that of several well-known UNIX
utilities.
This module is 8-bit clean: both patterns and strings may contain null
bytes and characters whose high bit is set.
*Please note:* There is a little-known fact about Python string
literals which means that you don't usually have to worry about
doubling backslashes, even though they are used to escape special
characters in string literals as well as in regular expressions. This
is because Python doesn't remove backslashes from string literals if
they are followed by an unrecognized escape character. *However*, if
you want to include a literal "backslash" in a regular expression
represented as a string literal, you have to *quadruple* it. E.g. to
extract LaTeX `\section{...}' headers from a document, you can use this
pattern: `'\\\\section{\(.*\)}''.
The module defines these functions, and an exception:
- function of module regex: match (PATTERN, STRING)
Return how many characters at the beginning of STRING match the
regular expression PATTERN. Return `-1' if the string does not
match the pattern (this is different from a zero-length match!).
- function of module regex: search (PATTERN, STRING)
Return the first position in STRING that matches the regular
expression PATTERN. Return -1 if no position in the string
matches the pattern (this is different from a zero-length match
anywhere!).
- function of module regex: compile (PATTERN, TRANSLATE)
Compile a regular expression pattern into a regular expression
object, which can be used for matching using its `match' and
`search' methods, described below. The optional TRANSLATE, if
present, must be a 256-character string indicating how characters
(both of the pattern and of the strings to be matched) are
translated before comparing them; the `i'-th element of the string
gives the translation for the character with ASCII code `i'.
The sequence
prog = regex.compile(pat)
result = prog.match(str)
is equivalent to
result = regex.match(pat, str)
but the version using `compile()' is more efficient when multiple
regular expressions are used concurrently in a single program.
(The compiled version of the last pattern passed to
`regex.match()' or `regex.search()' is cached, so programs that
use only a single regular expression at a time needn't worry about
compiling regular expressions.)
- function of module regex: set_syntax (FLAGS)
Set the syntax to be used by future calls to `compile', `match'
and `search'. (Already compiled expression objects are not
affected.) The argument is an integer which is the OR of several
flag bits. The return value is the previous value of the syntax
flags. Names for the flags are defined in the standard module
`regex_syntax'; read the file `regex_syntax.py' for more
information.
- function of module regex: symcomp (PATTERN, TRANSLATE)
This is like `compile', but supports symbolic group names: if a
parentheses-enclosed group begins with a group name in angular
brackets, e.g. `'\(<id>[a-z][a-z0-9]*\)'', the group can be
referenced by its name in arguments to the `group' method of the
resulting compiled regular expression object, like this:
`p.group('id')'.
- exception of module regex: error
Exception raised when a string passed to one of the functions here
is not a valid regular expression (e.g., unmatched parentheses) or
when some other error occurs during compilation or matching. (It
is never an error if a string contains no match for a pattern.)
- data of module regex: casefold
A string suitable to pass as TRANSLATE argument to `compile' to
map all upper case characters to their lowercase equivalents.
Compiled regular expression objects support these methods:
- Method on regex: match (STRING, POS)
Return how many characters at the beginning of STRING match the
compiled regular expression. Return `-1' if the string does not
match the pattern (this is different from a zero-length match!).
The optional second parameter POS gives an index in the string
where the search is to start; it defaults to `0'. This is not
completely equivalent to slicing the string; the `'^'' pattern
character matches at the real begin of the string and at positions
just after a newline, not necessarily at the index where the search
is to start.
- Method on regex: search (STRING, POS)
Return the first position in STRING that matches the regular
expression `pattern'. Return `-1' if no position in the string
matches the pattern (this is different from a zero-length match
anywhere!).
The optional second parameter has the same meaning as for the
`match' method.
- Method on regex: group (INDEX, INDEX, ...)
This method is only valid when the last call to the `match' or
`search' method found a match. It returns one or more groups of
the match. If there is a single INDEX argument, the result is a
single string; if there are multiple arguments, the result is a
tuple with one item per argument. If the INDEX is zero, the
corresponding return value is the entire matching string; if it is
in the inclusive range [1..99], it is the string matching the the
corresponding parenthesized group (using the default syntax,
groups are parenthesized using `
(' and `
)'). If no such group exists, the corresponding result is `None'.
If the regular expression was compiled by `symcomp' instead of
`compile', the INDEX arguments may also be strings identifying
groups by their group name.
Compiled regular expressions support these data attributes:
- attribute of regex: regs
When the last call to the `match' or `search' method found a
match, this is a tuple of pairs of indices corresponding to the
beginning and end of all parenthesized groups in the pattern.
Indices are relative to the string argument passed to `match' or
`search'. The 0-th tuple gives the beginning and end or the whole
pattern. When the last match or search failed, this is `None'.
- attribute of regex: last
When the last call to the `match' or `search' method found a
match, this is the string argument passed to that method. When the
last match or search failed, this is `None'.
- attribute of regex: translate
This is the value of the TRANSLATE argument to `regex.compile'
that created this regular expression object. If the TRANSLATE
argument was omitted in the `regex.compile' call, this is `None'.
- attribute of regex: givenpat
The regular expression pattern as passed to `compile' or `symcomp'.
- attribute of regex: realpat
The regular expression after stripping the group names for regular
expressions compiled with `symcomp'. Same as `givenpat' otherwise.
- attribute of regex: groupindex
A dictionary giving the mapping from symbolic group names to
numerical group indices for regular expressions compiled with
`symcomp'. `None' otherwise.
File: python-lib.info, Node: marshal, Next: struct, Prev: regex, Up: Built-in Modules
Built-in Module `marshal'
=========================
This module contains functions that can read and write Python values in
a binary format. The format is specific to Python, but independent of
machine architecture issues (e.g., you can write a Python value to a
file on a VAX, transport the file to a Mac, and read it back there).
Details of the format not explained here; read the source if you're
interested.(1)
Not all Python object types are supported; in general, only objects
whose value is independent from a particular invocation of Python can
be written and read by this module. The following types are supported:
`None', integers, long integers, floating point numbers, strings,
tuples, lists, dictionaries, and code objects, where it should be
understood that tuples, lists and dictionaries are only supported as
long as the values contained therein are themselves supported; and
recursive lists and dictionaries should not be written (they will cause
an infinite loop).
There are functions that read/write files as well as functions
operating on strings.
The module defines these functions:
- function of module marshal: dump (VALUE, FILE)
Write the value on the open file. The value must be a supported
type. The file must be an open file object such as `sys.stdout'
or returned by `open()' or `posix.popen()'.
If the value has an unsupported type, garbage is written which
cannot be read back by `load()'.
- function of module marshal: load (FILE)
Read one value from the open file and return it. If no valid value
is read, raise `EOFError', `ValueError' or `TypeError'. The file
must be an open file object.
- function of module marshal: dumps (VALUE)
Return the string that would be written to a file by `dump(value,
file)'. The value must be a supported type.
- function of module marshal: loads (STRING)
Convert the string to a value. If no valid value is found, raise
`EOFError', `ValueError' or `TypeError'. Extra characters in the
string are ignored.
---------- Footnotes ----------
(1) The name of this module stems from a bit of terminology used by
the designers of Modula-3 (amongst others), who use the term
"marshalling" for shipping of data around in a self-contained form.
Strictly speaking, "to marshal" means to convert some data from
internal to external form (in an RPC buffer for instance) and
"unmarshalling" for the reverse process.
File: python-lib.info, Node: struct, Prev: marshal, Up: Built-in Modules
Built-in module `struct'
========================
This module performs conversions between Python values and C structs
represented as Python strings. It uses "format strings" (explained
below) as compact descriptions of the lay-out of the C structs and the
intended conversion to/from Python values.
The module defines the following exception and functions:
- exception of module struct: error
Exception raised on various occasions; argument is a string
describing what is wrong.
- function of module struct: pack (FMT, V1, V2, ...)
Return a string containing the values `V1, V2, ...' packed
according to the given format. The arguments must match the
values required by the format exactly.
- function of module struct: unpack (FMT, STRING)
Unpack the string (presumably packed by `pack(FMT, ...)')
according to the given format. The result is a tuple even if it
contains exactly one item. The string must contain exactly the
amount of data required by the format (i.e. `len(STRING)' must
equal `calcsize(FMT)').
- function of module struct: calcsize (FMT)
Return the size of the struct (and hence of the string)
corresponding to the given format.
Format characters have the following meaning; the conversion between C
and Python values should be obvious given their types:
*Format*
*C* -- *Python*
`x'
pad byte -- no value
`c'
char -- string of length 1
`b'
signed char -- integer
`h'
short -- integer
`i'
int -- integer
`l'
long -- integer
`f'
float -- float
`d'
double -- float
A format character may be preceded by an integral repeat count; e.g.
the format string `'4h'' means exactly the same as `'hhhh''.
C numbers are represented in the machine's native format and byte
order, and properly aligned by skipping pad bytes if necessary
(according to the rules used by the C compiler).
Examples (all on a big-endian machine):
pack('hhl', 1, 2, 3) == '\000\001\000\002\000\000\000\003'
unpack('hhl', '\000\001\000\002\000\000\000\003') == (1, 2, 3)
calcsize('hhl') == 8
Hint: to align the end of a structure to the alignment requirement of a
particular type, end the format with the code for that type with a
repeat count of zero, e.g. the format `'llh0l'' specifies two pad bytes
at the end, assuming longs are aligned on 4-byte boundaries.
(More format characters are planned, e.g. `'s'' for character arrays,
upper case for unsigned variants, and a way to specify the byte order,
which is useful for [de]constructing network packets and
reading/writing portable binary file formats like TIFF and AIFF.)
File: python-lib.info, Node: Standard Modules, Next: UNIX ONLY, Prev: Built-in Modules, Up: Top
Standard Modules
****************
The modules described in this chapter are implemented in Python, but
are considered to be a part of Python's standard environment: they are
always available.(1)
* Menu:
* getopt::
* os::
* rand::
* regsub::
* string::
* whrandom::
---------- Footnotes ----------
(1) at least in theory -- it is possible to botch the library
installation or to sabotage the module search path so that these
modules cannot be found.
File: python-lib.info, Node: getopt, Next: os, Prev: Standard Modules, Up: Standard Modules
Standard Module `getopt'
========================
This module helps scripts to parse the command line arguments in
`sys.argv'. It uses the same conventions as the UNIX `getopt()'
function. It defines the function `getopt.getopt(args, options)' and
the exception `getopt.error'.
The first argument to `getopt()' is the argument list passed to the
script with its first element chopped off (i.e., `sys.argv[1:]'). The
second argument is the string of option letters that the script wants
to recognize, with options that require an argument followed by a colon
(i.e., the same format that UNIX `getopt()' uses). The return value
consists of two elements: the first is a list of option-and-value
pairs; the second is the list of program arguments left after the
option list was stripped (this is a trailing slice of the first
argument). Each option-and-value pair returned has the option as its
first element, prefixed with a hyphen (e.g., `'-x''), and the option
argument as its second element, or an empty string if the option has no
argument. The options occur in the list in the same order in which
they were found, thus allowing multiple occurrences. Example:
>>> import getopt, string
>>> args = string.split('-a -b -cfoo -d bar a1 a2')
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
>>>
The exception `getopt.error = 'getopt error'' is raised when an
unrecognized option is found in the argument list or when an option
requiring an argument is given none. The argument to the exception is
a string indicating the cause of the error.
File: python-lib.info, Node: os, Next: rand, Prev: getopt, Up: Standard Modules
Standard Module `os'
====================
This module provides a more portable way of using operating system (OS)
dependent functionality than importing an OS dependent built-in module
like `posix'.
When the optional built-in module `posix' is available, this module
exports the same functions and data as `posix'; otherwise, it searches
for an OS dependent built-in module like `mac' and exports the same
functions and data as found there. The design of all Python's built-in
OS dependen modules is such that as long as the same functionality is
available, it uses the same interface; e.g., the function
`os.stat(FILE)' returns stat info about a FILE in a format compatible
with the POSIX interface.
Extensions peculiar to a particular OS are also available through the
`os' module, but using them is of course a threat to portability!
Note that after the first time `os' is imported, there is *no*
performance penalty in using functions from `os' instead of directly
from the OS dependent built-in module, so there should be *no* reason
not to use `os'!
In addition to whatever the correct OS dependent module exports, the
following variables and functions are always exported by `os':
- data of module os: name
The name of the OS dependent module imported, e.g. `'posix'' or
`'mac''.
- data of module os: path
The corresponding OS dependent standard module for pathname
operations, e.g., `posixpath' or `macpath'. Thus, (given the
proper imports), `os.path.split(FILE)' is equivalent to but more
portable than `posixpath.split(FILE)'.
- data of module os: curdir
The constant string used by the OS to refer to the current
directory, e.g. `'.'' for POSIX or `':'' for the Mac.
- data of module os: pardir
The constant string used by the OS to refer to the parent
directory, e.g. `'..'' for POSIX or `'::'' for the Mac.
- data of module os: sep
The character used by the OS to separate pathname components, e.g.
`'/'' for POSIX or `':'' for the Mac. Note that knowing this is
not sufficient to be able to parse or concatenate pathnames--better
use `os.path.split()' and `os.path.join()'--but it is occasionally
useful.
- function of module os: execl (PATH, ARG0, ARG1, ...)
This is equivalent to a call to `os.execv' with an ARGV of `[ARG0,
ARG1, ...]'.
- function of module os: execle (PATH, ARG0, ARG1, ..., ENV)
This is equivalent to a call to `os.execve' with an ARGV of
`[ARG0, ARG1, ...]'.
- function of module os: execlp (PATH, ARG0, ARG1, ...)
This is like `execl' but duplicates the shell's actions in
searching for an executable file in a list of directories. The
directory list is obtained from `environ['PATH']'.
- function of module os: execvp (PATH, ARG0, ARG1, ...)
`execvp' is for `execv' what `execlp' is for `execl'.
File: python-lib.info, Node: rand, Next: regsub, Prev: os, Up: Standard Modules
Standard Module `rand'
======================
This module implements a pseudo-random number generator with an
interface similar to `rand()' in C. It defines the following functions:
- function of module rand: rand ()
Returns an integer random number in the range [0 ... 32768).
- function of module rand: choice (S)
Returns a random element from the sequence (string, tuple or list)
S.
- function of module rand: srand (SEED)
Initializes the random number generator with the given integral
seed. When the module is first imported, the random number is
initialized with the current time.
File: python-lib.info, Node: regsub, Next: string, Prev: rand, Up: Standard Modules
Standard Module `regsub'
========================
This module defines a number of functions useful for working with
regular expressions (see built-in module `regex').
- function of module regsub: sub (PAT, REPL, STR)
Replace the first occurrence of pattern PAT in string STR by
replacement REPL. If the pattern isn't found, the string is
returned unchanged. The pattern may be a string or an already
compiled pattern. The replacement may contain references `\DIGIT'
to subpatterns and escaped backslashes.
- function of module regsub: gsub (PAT, REPL, STR)
Replace all (non-overlapping) occurrences of pattern PAT in string
STR by replacement REPL. The same rules as for `sub()' apply.
Empty matches for the pattern are replaced only when not adjacent
to a previous match, so e.g. `gsub('', '-', 'abc')' returns
`'-a-b-c-''.
- function of module regsub: split (STR, PAT)
Split the string STR in fields separated by delimiters matching
the pattern PAT, and return a list containing the fields. Only
non-empty matches for the pattern are considered, so e.g.
`split('a:b', ':*')' returns `['a', 'b']' and `split('abc', '')'
returns `['abc']'.
File: python-lib.info, Node: string, Next: whrandom, Prev: regsub, Up: Standard Modules
Standard Module `string'
========================
This module defines some constants useful for checking character
classes, some exceptions, and some useful string functions. The
constants are:
- data of module string: digits
The string `'0123456789''.
- data of module string: hexdigits
The string `'0123456789abcdefABCDEF''.
- data of module string: letters
The concatenation of the strings `lowercase' and `uppercase'
described below.
- data of module string: lowercase
A string containing all the characters that are considered
lowercase letters. On most systems this is the string
`'abcdefghijklmnopqrstuvwxyz''. Do not change its definition -
the effect on the routines `upper' and `swapcase' is undefined.
- data of module string: octdigits
The string `'01234567''.
- data of module string: uppercase
A string containing all the characters that are considered
uppercase letters. On most systems this is the string
`'ABCDEFGHIJKLMNOPQRSTUVWXYZ''. Do not change its definition -
the effect on the routines `lower' and `swapcase' is undefined.
- data of module string: whitespace
A string containing all characters that are considered whitespace.
On most systems this includes the characters space, tab, linefeed,
return, formfeed, and vertical tab. Do not change its definition -
the effect on the routines `strip' and `split' is undefined.
The exceptions are:
- exception of module string: atof_error
Exception raised by `atof' when a non-float string argument is
detected. The exception argument is the offending string.
- exception of module string: atoi_error
Exception raised by `atoi' when a non-integer string argument is
detected. The exception argument is the offending string.
- exception of module string: atol_error
Exception raised by `atol' when a non-integer string argument is
detected. The exception argument is the offending string.
- exception of module string: index_error
Exception raised by `index' when SUB is not found. The exception
argument is undefined (it may be a tuple containing the offending
arguments to `index' or it may be the constant string `'substring
not found'').
The functions are:
- function of module string: atof (S)
Convert a string to a floating point number. The string must have
the standard syntax for a floating point literal in Python,
optionally preceded by a sign (`+' or `-').
- function of module string: atoi (S)
Convert a string to an integer. The string must consist of one or
more digits, optionally preceded by a sign (`+' or `-').
- function of module string: atol (S)
Convert a string to a long integer. The string must consist of one
or more digits, optionally preceded by a sign (`+' or `-').
- function of module string: expandtabs (S, TABSIZE)
Expand tabs in a string, i.e. replace them by one or more spaces,
depending on the current column and the given tab size. The column
number is reset to zero after each newline occurring in the string.
This doesn't understand other non-printing characters or escape
sequences.
- function of module string: find (S, SUB, I)
Return the lowest index in S not smaller than I where the
substring SUB is found. Return `-1' when SUB does not occur as a
substring of S with index at least I. If I is omitted, it
defaults to `0'. If I is negative, `len(S)' is added.
- function of module string: rfind (S, SUB, I)
Like `find' but finds the highest index.
- function of module string: index (S, SUB, I)
Like `find' but raise `index_error' when the substring is not
found.
- function of module string: rindex (S, SUB, I)
Like `rfind' but raise `index_error' when the substring is not
found.
- function of module string: lower (S)
Convert letters to lower case.
- function of module string: split (S)
Returns a list of the whitespace-delimited words of the string S.
- function of module string: splitfields (S, SEP)
Returns a list containing the fields of the string S, using the
string SEP as a separator. The list will have one more items than
the number of non-overlapping occurrences of the separator in the
string. Thus, `string.splitfields(S, ' ')' is not the same as
`string.split(S)', as the latter only returns non-empty words. As
a special case, `splitfields(S, '')' returns `[S]', for any string
S. (See also `regsub.split()'.)
- function of module string: join (WORDS)
Concatenate a list or tuple of words with intervening spaces.
- function of module string: joinfields (WORDS, SEP)
Concatenate a list or tuple of words with intervening separators.
It is always true that `string.joinfields(string.splitfields(T,
SEP), SEP)' equals T.
- function of module string: strip (S)
Removes leading and trailing whitespace from the string S.
- function of module string: swapcase (S)
Converts lower case letters to upper case and vice versa.
- function of module string: upper (S)
Convert letters to upper case.
- function of module string: ljust (S, WIDTH)
- function of module string: rjust (S, WIDTH)
- function of module string: center (S, WIDTH)
These functions respectively left-justify, right-justify and
center a string in a field of given width. They return a string
that is at least WIDTH characters wide, created by padding the
string S with spaces until the given width on the right, left or
both sides. The string is never truncated.
- function of module string: zfill (S, WIDTH)
Pad a numeric string on the left with zero digits until the given
width is reached. Strings starting with a sign are handled
correctly.
File: python-lib.info, Node: whrandom, Prev: string, Up: Standard Modules
Standard Module `whrandom'
==========================
This module implements a Wichmann-Hill pseudo-random number generator.
It defines the following functions:
- function of module whrandom: random ()
Returns the next random floating point number in the range [0.0
... 1.0).
- function of module whrandom: seed (X, Y, Z)
Initializes the random number generator from the integers X, Y and
Z. When the module is first imported, the random number is
initialized using values derived from the current time.
File: python-lib.info, Node: UNIX ONLY, Next: MULTIMEDIA EXTENSIONS, Prev: Standard Modules, Up: Top
UNIX ONLY
*********
The modules described in this chapter provide interfaces to features
that are unique to the UNIX operating system, or in some cases to some
or many variants of it.
* Menu:
* dbm::
* grp::
* posix::
* posixpath::
* pwd::
* select::
* socket::
* thread::
File: python-lib.info, Node: dbm, Next: grp, Prev: UNIX ONLY, Up: UNIX ONLY
Built-in Module `dbm'
=====================
Dbm provides python programs with an interface to the unix `ndbm'
database library. Dbm objects are of the mapping type, so they can be
handled just like objects of the built-in "dictionary" type, except
that keys and values are always strings, and printing a dbm object
doesn't print the keys and values.
The module defines the following constant and functions:
- exception of module dbm: error
Raised on dbm-specific errors, such as I/O errors. `KeyError' is
raised for general mapping errors like specifying an incorrect key.
- function of module dbm: open (FILENAME, RWMODE, FILEMODE)
Open a dbm database and return a mapping object. FILENAME is the
name of the database file (without the `.dir' or `.pag'
extensions), RWMODE is `'r'', `'w'' or `'rw'' as for `open', and
FILEMODE is the unix mode of the file, used only when the database
has to be created.
File: python-lib.info, Node: grp, Next: posix, Prev: dbm, Up: UNIX ONLY
Built-in Module `grp'
=====================
This module provides access to the UNIX group database. It is
available on all UNIX versions.
Group database entries are reported as 4-tuples containing the
following items from the group database (see `<grp.h>'), in order:
`gr_name', `gr_passwd', `gr_gid', `gr_mem'. The gid is an integer,
name and password are strings, and the member list is a list of strings.
(Note that most users are not explicitly listed as members of the
group(s) they are in.) An exception is raised if the entry asked for
cannot be found.
It defines the following items:
- function of module grp: getgrgid (GID)
Return the group database entry for the given numeric group ID.
- function of module grp: getgrnam (NAME)
Return the group database entry for the given group name.
- function of module grp: getgrall ()
Return a list of all available group entries entries, in arbitrary
order.
File: python-lib.info, Node: posix, Next: posixpath, Prev: grp, Up: UNIX ONLY
Built-in Module `posix'
=======================
This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly diguised
UNIX interface). It is available in all Python versions except on the
Macintosh; the MS-DOS version does not support certain functions. The
descriptions below are very terse; refer to the corresponding UNIX
manual entry for more information.
Errors are reported as exceptions; the usual exceptions are given for
type errors, while errors reported by the system calls raise
`posix.error', described below.
Module `posix' defines the following data items:
- data of module posix: environ
A dictionary representing the string environment at the time the
interpreter was started. (Modifying this dictionary does not
affect the string environment of the interpreter.) For example,
`posix.environ['HOME']' is the pathname of your home directory,
equivalent to `getenv("HOME")' in C.
- exception of module posix: error
This exception is raised when an POSIX function returns a
POSIX-related error (e.g., not for illegal argument types). Its
string value is `'posix.error''. The accompanying value is a pair
containing the numeric error code from `errno' and the
corresponding string, as would be printed by the C function
`perror()'.
It defines the following functions:
- function of module posix: chdir (PATH)
Change the current working directory to PATH.
- function of module posix: chmod (PATH, MODE)
Change the mode of PATH to the numeric MODE.
- function of module posix: close (FD)
Close file descriptor FD.
- function of module posix: dup (FD)
Return a duplicate of file descriptor FD.
- function of module posix: dup2 (FD, FD2)
Duplicate file descriptor FD to FD2, closing the latter first if
necessary. Return `None'.
- function of module posix: execv (PATH, ARGS)
Execute the executable PATH with argument list ARGS, replacing the
current process (i.e., the Python interpreter). The argument list
may be a tuple or list of strings. (Not on MS-DOS.)
- function of module posix: execve (PATH, ARGS, ENV)
Execute the executable PATH with argument list ARGS, and
environment ENV, replacing the current process (i.e., the Python
interpreter). The argument list may be a tuple or list of strings.
The environment must be a dictionary mapping strings to strings.
(Not on MS-DOS.)
- function of module posix: _exit (N)
Exit to the system with status N, without calling cleanup
handlers, flushing stdio buffers, etc. (Not on MS-DOS.)
Note: the standard way to exit is `sys.exit(N)'. `posix._exit()'
should normally only be used in the child process after a `fork()'.
- function of module posix: fdopen (FD, MODE)
Return an open file object connected to the file descriptor FD,
open for reading and/or writing according to the MODE string
(which has the same meaning as the MODE argument to the built-in
`open()' function.
- function of module posix: fork ()
Fork a child process. Return 0 in the child, the child's process
id in the parent. (Not on MS-DOS.)
- function of module posix: fstat (FD)
Return status for file descriptor FD, like `stat()'.
- function of module posix: getcwd ()
Return a string representing the current working directory.
- function of module posix: getegid ()
Return the current process's effective group id. (Not on MS-DOS.)
- function of module posix: geteuid ()
Return the current process's effective user id. (Not on MS-DOS.)
- function of module posix: getgid ()
Return the current process's group id. (Not on MS-DOS.)
- function of module posix: getpid ()
Return the current process id. (Not on MS-DOS.)
- function of module posix: getppid ()
Return the parent's process id. (Not on MS-DOS.)
- function of module posix: getuid ()
Return the current process's user id. (Not on MS-DOS.)
- function of module posix: kill (PID, SIG)
Kill the process PID with signal SIG. (Not on MS-DOS.)
- function of module posix: link (SRC, DST)
Create a hard link pointing to SRC named DST. (Not on MS-DOS.)
- function of module posix: listdir (PATH)
Return a list containing the names of the entries in the directory.
The list is in arbitrary order. It includes the special entries
`'.'' and `'..'' if they are present in the directory.
- function of module posix: lseek (FD, POS, HOW)
Set the current position of file descriptor FD to position POS,
modified by HOW: 0 to set the position relative to the beginning
of the file; 1 to set it relative to the current position; 2 to
set it relative to the end of the file.
- function of module posix: lstat (PATH)
Like `stat()', but do not follow symbolic links. (On systems
without symbolic links, this is identical to `posix.stat'.)
- function of module posix: mkdir (PATH, MODE)
Create a directory named PATH with numeric mode MODE.
- function of module posix: nice (INCREMENT)
Add INCR to the process' "niceness". Return the new niceness.
(Not on MS-DOS.)
- function of module posix: open (FILE, FLAGS, MODE)
Open the file FILE and set various flags according to FLAGS and
possibly its mode according to MODE. Return the file descriptor
for the newly opened file.
- function of module posix: pipe ()
Create a pipe. Return a pair of file descriptors `(r, w)' usable
for reading and writing, respectively. (Not on MS-DOS.)
- function of module posix: popen (COMMAND, MODE)
Open a pipe to or from COMMAND. The return value is an open file
object connected to the pipe, which can be read or written
depending on whether MODE is `'r'' or `'w''. (Not on MS-DOS.)
- function of module posix: read (FD, N)
Read at most N bytes from file descriptor FD. Return a string
containing the bytes read.
- function of module posix: readlink (PATH)
Return a string representing the path to which the symbolic link
points. (On systems without symbolic links, this always raises
`posix.error'.)
- function of module posix: rename (SRC, DST)
Rename the file or directory SRC to DST.
- function of module posix: rmdir (PATH)
Remove the directory PATH.
- function of module posix: setgid (GID)
Set the current process's group id. (Not on MS-DOS.)
- function of module posix: setuid (UID)
Set the current process's user id. (Not on MS-DOS.)
- function of module posix: stat (PATH)
Perform a *stat* system call on the given path. The return value
is a tuple of at least 10 integers giving the most important (and
portable) members of the *stat* structure, in the order `st_mode',
`st_ino', `st_dev', `st_nlink', `st_uid', `st_gid', `st_size',
`st_atime', `st_mtime', `st_ctime'. More items may be added at
the end by some implementations. (On MS-DOS, some items are
filled with dummy values.)
Note: The standard module `stat' defines functions and constants
that are useful for extracting information from a stat structure.
- function of module posix: symlink (SRC, DST)
Create a symbolic link pointing to SRC named DST. (On systems
without symbolic links, this always raises `posix.error'.)
- function of module posix: system (COMMAND)
Execute the command (a string) in a subshell. This is implemented
by calling the Standard C function `system()', and has the same
limitations. Changes to `posix.environ', `sys.stdin' etc. are not
reflected in the environment of the executed command. The return
value is the exit status of the process as returned by Standard C
`system()'.
- function of module posix: times ()
Return a 4-tuple of floating point numbers indicating accumulated
CPU times, in seconds. The items are: user time, system time,
children's user time, and children's system time, in that order.
See the UNIX manual page times(2). (Not on MS-DOS.)
- function of module posix: umask (MASK)
Set the current numeric umask and returns the previous umask.
(Not on MS-DOS.)
- function of module posix: uname ()
Return a 5-tuple containing information identifying the current
operating system. The tuple contains 5 strings: `(SYSNAME,
NODENAME, RELEASE, VERSION, MACHINE)'. Some systems truncate the
nodename to 8 characters or to the leading component; an better
way to get the hostname is `socket.gethostname()'. (Not on
MS-DOS, nor on older UNIX systems.)
- function of module posix: unlink (PATH)
Unlink PATH.
- function of module posix: utime (PATH, (ATIME, MTIME))
Set the access and modified time of the file to the given values.
(The second argument is a tuple of two items.)
- function of module posix: wait ()
Wait for completion of a child process, and return a tuple
containing its pid and exit status indication (encoded as by UNIX).
(Not on MS-DOS.)
- function of module posix: waitpid (PID, OPTIONS)
Wait for completion of a child process given by proces id, and
return a tuple containing its pid and exit status indication
(encoded as by UNIX). The semantics of the call are affected by
the value of the integer options, which should be 0 for normal
operation. (If the system does not support waitpid(), this always
raises `posix.error'. Not on MS-DOS.)
- function of module posix: write (FD, STR)
Write the string STR to file descriptor FD. Return the number of
bytes actually written.